package pers.qianyu.diytomcat.servlets;

import cn.hutool.core.io.*;
import cn.hutool.core.thread.*;
import cn.hutool.core.util.*;
import pers.qianyu.diytomcat.constants.*;
import pers.qianyu.diytomcat.http.*;
import pers.qianyu.diytomcat.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * @author mizzle rain
 * @date 2021-01-08 15:56
 */
public class DefaultServlet extends HttpServlet {
    private DefaultServlet() {
    }

    private static final DefaultServlet INSTANCE = new DefaultServlet();

    public static synchronized DefaultServlet getInstance() {
        return INSTANCE;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        Request request = (Request) req;
        Response response = (Response) res;

        String uri = request.getUri();
        if (Objects.equals("/timeConsume.html", uri)) {
            ThreadUtil.sleep(1000);
        }
        if (Objects.equals("/500.html", uri)) {
            throw new RuntimeException("this is a deliberately created exception");
        }

        String fileName;
        if (Objects.equals("/", uri)) {
            fileName = WebXmlUtil.getWelcomeFile(request.getContext());
        } else {
            fileName = StrUtil.subAfter(uri, "/", false);
        }
        if (fileName.endsWith(".jsp")) {
            JspServlet.getInstance().service(req, res);
            return;
        }
        File file = FileUtil.file(request.getRealPath(fileName));
        if (file.exists()) {
            // 根据文件名设置 Content-Type
            String extName = FileUtil.extName(file);
            response.setContentType(WebXmlUtil.getMimeType(extName));
            byte[] bytes = FileUtil.readBytes(file);
            response.setBody(bytes);
            response.setStatus(HttpCode.CODE_200);
        } else {
            response.setStatus(HttpCode.CODE_404);
        }
    }
}
